# coding=utf-8
import requests
import json
from urllib import parse
from base.get_headers import GetHeaders

# 测试地址
test_url = ''
# 登录地址
login_url = ''

class ApiRequest(object):


    def __init__(self):
        self.is_cookie = self.__check_cookie()
        if not self.is_cookie:
            print(">>>>cookie验证失败，正在重新获取cookie")
            if GetHeaders().main():
                self.header, self.csrfcode = self.__read_cookie()
                self.is_cookie = True
                print(">>>>>>cookie获取成功，正在初始化请求头")
        else:
            print('>>>>cookie验证成功')

    def api_request(self, url, data=None, head=None, flag=False, method='post'):
        # 是否更新头部信息
        if head:
            self.header.update(head)
        # 是否编码
        if flag:
            data = parse.urlencode(data)
            print(data)
        try:
            # 校验Cooke是否失效
            if self.is_cookie:
                if method == 'post':
                    res = requests.post(url=url, data=data, headers=self.header)
                    if res.status_code in [200]:
                        return json.loads(res.content.decode())
                    else:
                        print("状态码:{}\n返回信息：{}".format(res.status_code, res.content.decode()))
                elif method.lower() == 'get':
                    res = requests.get(url=url, headers=self.header)
                    if res.status_code in [200]:
                        return json.loads(res.content.decode())
                    else:
                        print("状态码:{}\n返回信息：{}".format(res.status_code, res.content.decode()))
            else:
                print("未知错误")
        except Exception as e:
            print("请求出现错误\n\t{}\n>>>>请求头信息{}\n返回信息{}".format(e, head, res.content.decode()))

    #校验cookie
    def __check_cookie(self):
        '''
            尝试去访问查询接口，如果cookie过期会返回过期相关的信息
            :return: bool
        '''
        url = 'https://106.55.243.240/index.html#/'
        res = requests.post(url=url, headers=self.header, method='get')
        if 'data' in res.content.decode():
            return True
        else:
            print('状态码：{}\n返回结果：{}'.format(res.status_code, res.content.decode()))
            return False

    # 文件读取cookie
    def __read_cookie(self):
        with open('header.json', 'r', encoding='utf-8') as fp:
            data = json.loads(fp.read())
            head = data['header']
            code = data['code']
        return head, code

    #测试
    def test(self):
        url = 'https://106.55.243.240/index.html#/'
        res = self.api_request(url=url, data=json.dumps(data), method='get')
        print(res)


if __name__ == '__main__':
    import time
    print(time.time())
    # ApiRequest().test()

